@{
    ViewData["Title"] = "选择用户";
    string selectedIds = ViewBag.SelectedIds as string ?? "";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>@ViewData["Title"]</title>
    <link rel="stylesheet" href="~/layui/css/layui.css">
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>选择班组成员</h3>
                </div>
                <div class="layui-card-body">
                    <!-- 搜索条件 -->
                    <div class="layui-form layui-form-pane" lay-filter="searchForm">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">关键字</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="keyword" placeholder="用户名、昵称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
                                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                            </div>
                        </div>
                    </div>

                    <!-- 工具栏 -->
                    <div class="layui-row" style="margin-bottom: 10px;">
                        <div class="layui-col-md12">
                            <button type="button" class="layui-btn layui-btn-sm" id="btnSelectAll">全选</button>
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btnUnselectAll">取消全选</button>
                            <span style="margin-left: 20px; color: #666;">
                                已选择 <span id="selectedCount">0</span> 人
                            </span>
                        </div>
                    </div>

                    <!-- 数据表格 -->
                    <table class="layui-hide" id="userTable" lay-filter="userTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/layui/layui.js"></script>

<script>
    layui.use(['table', 'form'], function () {
        var table = layui.table;
        var form = layui.form;

        var selectedIds = '@selectedIds'.split(',').filter(function(id) { return id.trim() !== ''; }).map(function(id) { return parseInt(id); });
        var selectedUsers = [];
        
        console.log('初始化 selectedIds:', selectedIds);

        // 渲染表格
        var tableIns = table.render({
            elem: '#userTable',
            url: '/Team/GetUserSelectList',
            contentType: 'application/json',
            method: 'POST',
            page: true,
            height: 400,
            cols: [[
                { 
                    field: 'checkbox', 
                    title: '选择',
                    width: 80,
                    fixed: 'left',
                    templet: function(d) {
                        var checked = selectedIds.indexOf(d.id) > -1 ? 'checked' : '';
                        return '<input type="checkbox" name="userSelect" value="' + d.id + '" lay-skin="primary" lay-filter="userSelect" ' + checked + '>';
                    }
                },
                { field: 'id', title: 'ID', width: 80, sort: true },
                { field: 'username', title: '用户名', width: 150 },
                { field: 'userNickname', title: '昵称', width: 150 },
                { 
                    field: 'isSelected', 
                    title: '状态', 
                    width: 100,
                    templet: function(d) {
                        return selectedIds.indexOf(d.id) > -1 ? '<span class="layui-badge layui-bg-blue">已选择</span>' : '<span class="layui-badge layui-bg-gray">未选择</span>';
                    }
                }
            ]],
            request: {
                pageName: 'page',
                limitName: 'pageSize'
            },
            where: {
                page: 1,
                pageSize: 10,
                sorting: 'Username',
                selectedUserIds: selectedIds
            },
            parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data
                };
            },
            done: function(res, curr, count) {
                console.log('表格渲染完成，数据:', res);
                // 表格渲染完成后，更新checkbox状态
                updateCheckboxState();
                updateSelectedCount();
                
                // 延迟执行，确保DOM完全渲染
                setTimeout(function() {
                    // 确保所有已选中的checkbox对应的用户ID都在selectedIds中
                    $('input[name="userSelect"]:checked').each(function() {
                        var userId = parseInt($(this).val());
                        if (selectedIds.indexOf(userId) === -1) {
                            selectedIds.push(userId);
                            console.log('表格渲染后添加用户ID到selectedIds:', userId);
                        }
                    });
                    console.log('表格渲染完成后的selectedIds:', selectedIds);
                    updateSelectedCount();
                }, 100);
            }
        });

        // 更新checkbox状态
        function updateCheckboxState() {
            console.log('更新checkbox状态，selectedIds:', selectedIds);
            $('input[name="userSelect"]').each(function() {
                var userId = parseInt($(this).val());
                var shouldBeChecked = selectedIds.indexOf(userId) > -1;
                console.log('用户ID:', userId, '应该选中:', shouldBeChecked, '当前状态:', $(this).is(':checked'));
                
                if (shouldBeChecked) {
                    $(this).prop('checked', true);
                    // 同时更新selectedIds（如果还没有的话）
                    if (selectedIds.indexOf(userId) === -1) {
                        selectedIds.push(userId);
                    }
                } else {
                    $(this).prop('checked', false);
                }
            });
            form.render('checkbox');
            console.log('checkbox状态更新完成，最终selectedIds:', selectedIds);
        }

        // 更新选中计数
        function updateSelectedCount() {
            $('#selectedCount').text(selectedIds.length);
        }

        // 监听checkbox变化 - 使用layui的form监听
        form.on('checkbox(userSelect)', function(data) {
            var userId = parseInt(data.value);
            var isChecked = data.elem.checked;
            
            console.log('layui checkbox变化 - 用户ID:', userId, '选中状态:', isChecked);
            
            if (isChecked) {
                if (selectedIds.indexOf(userId) === -1) {
                    selectedIds.push(userId);
                    console.log('添加用户ID到selectedIds:', userId);
                }
            } else {
                var index = selectedIds.indexOf(userId);
                if (index > -1) {
                    selectedIds.splice(index, 1);
                    console.log('从selectedIds中移除用户ID:', userId);
                }
            }
            
            console.log('当前selectedIds:', selectedIds);
            updateSelectedCount();
            
            // 更新当前行的状态显示
            var $row = $(data.elem).closest('tr');
            var statusCell = $row.find('td').eq(4);
            if (isChecked) {
                statusCell.html('<span class="layui-badge layui-bg-blue">已选择</span>');
            } else {
                statusCell.html('<span class="layui-badge layui-bg-gray">未选择</span>');
            }
        });

        // 备用的原生事件监听（以防layui事件不工作）
        $(document).on('change', 'input[name="userSelect"]', function() {
            var userId = parseInt($(this).val());
            var isChecked = $(this).is(':checked');
            
            console.log('checkbox变化 - 用户ID:', userId, '选中状态:', isChecked);
            
            if (isChecked) {
                if (selectedIds.indexOf(userId) === -1) {
                    selectedIds.push(userId);
                    console.log('添加用户ID到selectedIds:', userId);
                }
            } else {
                var index = selectedIds.indexOf(userId);
                if (index > -1) {
                    selectedIds.splice(index, 1);
                    console.log('从selectedIds中移除用户ID:', userId);
                }
            }
            
            console.log('当前selectedIds:', selectedIds);
            updateSelectedCount();
            
            // 更新当前行的状态显示，而不是重新加载整个表格
            var $row = $(this).closest('tr');
            var statusCell = $row.find('td').eq(4); // 状态列是第5列（索引4）
            if (isChecked) {
                statusCell.html('<span class="layui-badge layui-bg-blue">已选择</span>');
            } else {
                statusCell.html('<span class="layui-badge layui-bg-gray">未选择</span>');
            }
        });

        // 搜索
        form.on('submit(search)', function (data) {
            var field = data.field;
            tableIns.reload({
                where: {
                    keyword: field.keyword,
                    page: 1,
                    pageSize: 10,
                    sorting: 'Username',
                    selectedUserIds: selectedIds
                },
                page: {
                    curr: 1
                }
            });
            return false;
        });

        // 全选
        $('#btnSelectAll').on('click', function() {
            // 获取当前页所有用户ID
            var tableData = table.cache.userTable;
            if (tableData && tableData.length > 0) {
                console.log('全选操作，当前页数据:', tableData);
                tableData.forEach(function(item) {
                    if (selectedIds.indexOf(item.id) === -1) {
                        selectedIds.push(item.id);
                        console.log('全选添加用户ID:', item.id);
                    }
                });
                updateSelectedCount();
                
                // 更新当前页所有checkbox状态
                $('input[name="userSelect"]').each(function() {
                    $(this).prop('checked', true);
                    var $row = $(this).closest('tr');
                    var statusCell = $row.find('td').eq(4);
                    statusCell.html('<span class="layui-badge layui-bg-blue">已选择</span>');
                });
                form.render('checkbox');
                console.log('全选后的selectedIds:', selectedIds);
            }
        });

        // 取消全选
        $('#btnUnselectAll').on('click', function() {
            console.log('取消全选操作');
            selectedIds = [];
            updateSelectedCount();
            
            // 更新当前页所有checkbox状态
            $('input[name="userSelect"]').each(function() {
                $(this).prop('checked', false);
                var $row = $(this).closest('tr');
                var statusCell = $row.find('td').eq(4);
                statusCell.html('<span class="layui-badge layui-bg-gray">未选择</span>');
            });
            form.render('checkbox');
            console.log('取消全选后的selectedIds:', selectedIds);
        });

        // 提供给父页面调用的方法
        window.getSelectedUsers = function() {
            console.log('getSelectedUsers被调用，selectedIds:', selectedIds);
            
            // 首先手动检查当前页面上实际选中的checkbox
            var actualSelectedIds = [];
            $('input[name="userSelect"]:checked').each(function() {
                var userId = parseInt($(this).val());
                if (actualSelectedIds.indexOf(userId) === -1) {
                    actualSelectedIds.push(userId);
                }
            });
            console.log('实际选中的用户ID:', actualSelectedIds);
            
            // 使用实际选中的ID
            if (actualSelectedIds.length > 0) {
                selectedIds = actualSelectedIds;
            }
            
            // 如果没有选中任何用户，直接返回空数组
            if (!selectedIds || selectedIds.length === 0) {
                console.log('没有选中的用户');
                return [];
            }
            
            // 获取当前选中的用户信息
            var users = [];
            var tableData = table.cache.userTable || [];
            console.log('表格缓存数据:', tableData);
            
            selectedIds.forEach(function(id) {
                var user = tableData.find(function(item) { return item.id === id; });
                if (user) {
                    users.push({
                        id: user.id,
                        username: user.username,
                        userNickname: user.userNickname
                    });
                }
            });
            
            console.log('从表格缓存中找到的用户:', users);
            
            // 如果当前页没有某些用户数据，我们需要通过AJAX获取完整的用户信息
            if (users.length < selectedIds.length) {
                console.log('需要通过AJAX获取完整用户信息');
                // 同步获取所有选中用户的完整信息
                $.ajax({
                    url: '/Team/GetSelectedUsersInfo',
                    type: 'POST',
                    async: false,
                    contentType: 'application/json',
                    data: JSON.stringify({ UserIds: selectedIds }),
                    success: function(res) {
                        console.log('AJAX响应:', res);
                        if (res.code === 0) {
                            users = res.data;
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX请求失败:', error);
                    }
                });
            }
            
            console.log('最终返回的用户数据:', users);
            return users;
        };
    });
</script>
</body>
</html> 